<template>
  <div class="login-container">
    <n-card title="管理后台登录">
      <n-form :rules="rules" :model="admin">
        <n-form-item path="account" label="账号">
          <n-input v-model:value="admin.account" placeholder="请输入账号"></n-input>
        </n-form-item>
        <n-form-item path="password" label="密码">
          <n-input v-model:value="admin.password" type="password" placeholder="请输入密码"></n-input>
        </n-form-item>
      </n-form>
      <template #footer>
        <n-checkbox v-model:checked="admin.rember" label="记住我"></n-checkbox>
        <n-button @click="goLogin">登录</n-button>
      </template>
    </n-card>
  </div>
</template>

<script setup>
import { reactive, inject } from 'vue'
import { NCard, NCheckbox, NForm, NInput, NButton, NFormItem } from 'naive-ui'
import { useRouter, useRoute } from 'vue-router'
import { AdminStore } from '../store/adminStore'

const axios = inject('axios')
const message = inject('message')
const router = useRouter()
const adminStore = AdminStore()
console.log('adminStore', adminStore);

let rules = {
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 12, message: '账号长度在3到12个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 18, message: '账号长度在6到18个字符', trigger: 'blur' }
  ],
}
const admin = reactive({
  account: localStorage.getItem('username') || '',
  password: localStorage.getItem('password') || '',
  rember: localStorage.getItem('rember') == 1 || false
})
// 登录请求方法
async function goLogin() {
  let result = await axios.get('/api/users/login', {
    params: {
      username: admin.account,
      password: admin.password
    }
  })
  // console.log('登录请求', result);
  // console.log(' result.data', result.data);
  if (result.data.msg == '登陆成功') {
    adminStore.username = result.data.username
    // console.log('adminStore.username',adminStore.username);
    adminStore.nickname = result.data.nickname
    // console.log('adminStore.nickname',adminStore.nickname);
    adminStore.token = result.data.token
    adminStore.headImgUrl = result.data.headImgUrl
    localStorage.setItem('token', adminStore.token)
    localStorage.setItem('headImgUrl', adminStore.headImgUrl)
    localStorage.setItem('uid', result.data.uid)
    // console.log('adminStore.token',adminStore.token);
    if (admin.rember) {
      localStorage.setItem('username', admin.account)
      localStorage.setItem('password', admin.password)
      localStorage.setItem('rember', admin.rember ? 1 : 0)
    }
    router.push('/backstage')
    message.success('登陆成功')
  } else {
    message.error('登陆失败')
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  width: 500px;
  margin: 0 auto;
}
</style>